package warriorCombat;


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.FlowLayout;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.File;
import java.net.Socket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.ImageIcon;
import javax.swing.JTextArea;
import javax.swing.JTextField;

/**
 *Displays Client arena options showing currently available warriors and providing an interface to attack other warriors
 *
 *@author Brett Hoyer
 */
@SuppressWarnings("serial")
public class ArenaClient extends JFrame implements ActionListener, Runnable
{
	//Server
	private Socket server;
	final private static int PORT = 8001;
	private PrintWriter out;
	private BufferedReader in;

	//Local Warrior
	private Warrior localWarrior;
	private JLabel lblHealth = new JLabel();;
	private JTable tblOpponents;
	private JPanel pnlOpponents;

	//Opponents
	private ArrayList<Warrior> arylOpponents;

	//Attack Options
	private final String ATTACK1 = "Rock";
	private final String ATTACK2 = "Paper";
	private final String ATTACK3 = "Scissors";
	private boolean inCombat = false;

	/**
	 * Constructor
	 * Receives the server connection from the LoadWarrior class and creates then displays the GUI
	 * @param server socket connection to server
	 * @param localWarrior warrior for local client
	 */
	public ArenaClient(Socket server, Warrior localWarrior)
	{
		this.server = server;
		this.setTitle(localWarrior.getName());

		try
		{
			out = new PrintWriter(this.server.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(this.server.getInputStream()));
			out.println(localWarrior.toStringFull());
			updateLocalWarrior(in.readLine());
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}

		JPanel pnl = new JPanel(new BorderLayout());

		//Set up and Add current Warrior Display
		pnl.add(setUpLocalWarriorPanel(), BorderLayout.EAST);
		pnl.add(setUpCombatControlPanel(), BorderLayout.CENTER);
		pnl.add(setUpWarriorTable(), BorderLayout.WEST);
		this.add(pnl);

		this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
		this.addWindowListener(new WindowListener(){
			@Override
			public void windowClosed(WindowEvent arg0) {}
			@Override
			public void windowClosing(WindowEvent arg0) {
				exitApplication();
			}
			@Override
			public void windowDeactivated(WindowEvent arg0) {}
			@Override
			public void windowDeiconified(WindowEvent arg0) {}
			@Override
			public void windowIconified(WindowEvent arg0) {}
			@Override
			public void windowOpened(WindowEvent arg0) {}
			@Override
			public void windowActivated(WindowEvent e) {}
		});

		//Display frame
		this.pack();
		this.setLocationRelativeTo(null);
		this.setVisible(true);

		JOptionPane.showMessageDialog(this,
				this.localWarrior.getName() + ", welcome to the field of battle!",
				"Prepare for combat",
				JOptionPane.INFORMATION_MESSAGE,
				LoadWarrior.getTurtle());

		ExecutorService worker = Executors.newFixedThreadPool(1);
		worker.execute(this);
	}

	/**
	 * Notifies player that they have been attacked and gets defense
	 * @param in attackers name
	 */
	private void getDefense(String in)
	{
		Object[] options = {ATTACK1, ATTACK2, ATTACK3};
		int n = JOptionPane.showOptionDialog(this,
				"You have been attacked by " + in + "!!\nChoose your counter-attack.",
				"INCOMING ATTACK!!",
				JOptionPane.YES_NO_CANCEL_OPTION,
				JOptionPane.QUESTION_MESSAGE,
				LoadWarrior.getTurtle(),
				options,
				options[0]);

		String def = "DEFENSE;";
		switch (n)
		{
		case 0:
			def += ATTACK1;
			break;
		case 1:
			def += ATTACK2;
			break;
		case 2:
			def += ATTACK3;
			break;
		}

		out.println(def);
	}

	/**
	 * Returns port for server connection
	 * @return port
	 */
	public static int getPort()
	{
		return PORT;
	}

	/**
	 * Contacts Combat Moderator to initiate combat
	 * @param atk Attack performed by local warrior
	 */
	private void commenceAttack(String atk)
	{
		if(inCombat)
			JOptionPane.showMessageDialog(this,
					"Finish fighting one opponent before attacking another.",
					"You are Spunky",
					JOptionPane.INFORMATION_MESSAGE,
					LoadWarrior.getTurtle());
		else
		{
			if(tblOpponents.getSelectedRow() != -1)
			{
				int ser = Integer.parseInt((tblOpponents.getModel().getValueAt(tblOpponents.getSelectedRow(), 4)+""));
				if(ser == localWarrior.getSerial())
					JOptionPane.showMessageDialog(this,
							"You cannot attack yourself.",
							"Watch where you're Aimining!",
							JOptionPane.INFORMATION_MESSAGE,
							LoadWarrior.getTurtle());
				else
				{
					inCombat = true;
					String attack = "ATTACK;" + localWarrior.getSerial() + ";" + localWarrior.getName() + ";" + atk + ";";
					attack += tblOpponents.getModel().getValueAt(tblOpponents.getSelectedRow(), 4) + ";";
					attack += tblOpponents.getModel().getValueAt(tblOpponents.getSelectedRow(), 0) + ";";
					out.println(attack);
				}
			}
		}
	}

	/**
	 * Creates an Array of combatants based on a given string
	 * @param list String containing list of combatants
	 */
	private void createOpponentsArray(String list)
	{
		arylOpponents = new ArrayList<Warrior>();
		String delim = "[;]+";
		String[] in = list.split(delim, 7);
		while(in.length > 6)
		{
			arylOpponents.add(new Warrior(in[0] + ";" + in[1] + ";" + in[2] + ";" + in[3] + ";" + in[4] + ";", Integer.parseInt(in[5])));
			in = in[6].split(delim, 7);
		}
		if(in.length == 6)
			arylOpponents.add(new Warrior(in[0] + ";" + in[1] + ";" + in[2] + ";" + in[3] + ";" + in[4] + ";", Integer.parseInt(in[5])));

	}

	/**
	 * Updates local warrior with a warrior provided by the server
	 * @param in string representation of warrior
	 */
	private void updateLocalWarrior(String in)
	{
		String delim = "[;]+";
		String[] str = in.split(delim);
		this.localWarrior = new Warrior(str[0] + ";" + str[1] + ";" + str[2] + ";" + str[3] + ";" + str[4] + ";", Integer.parseInt(str[5]));
		updateHealthDisplay();
	}

	/**
	 * Updates health display to reflect current health of local warrior
	 * Disconnects client if health drops below zero
	 */
	private void updateHealthDisplay()
	{
		if(Integer.parseInt(localWarrior.getHealth()) < 1)
		{
			JOptionPane.showMessageDialog(this,
					"You have fallen in battle, please be more carefull next time.",
					"Come back soon.",
					JOptionPane.INFORMATION_MESSAGE,
					LoadWarrior.getTurtle());
			exitApplication();
		}
		SwingUtilities.invokeLater(
				new Runnable()
				{
					public void run()
					{
						lblHealth.setText(" Health: " + localWarrior.getHealth());
					}
				});
	}

	/**
	 * Updates the Table to display all warriors currently listed
	 * in arylOpponents
	 */
	private void updateOpponentTable(String input)
	{

		createOpponentsArray(input);


		DefaultTableModel tableModel = (DefaultTableModel) tblOpponents.getModel();

		while(tableModel.getRowCount() != 0)
			tableModel.removeRow(0);

		for (int i=0; i<arylOpponents.size(); i++)
			tableModel.addRow(arylOpponents.get(i).getTableData());

		this.tblOpponents.setModel(tableModel);
	}

	/**
	 * Displays results of combat action
	 * @param in string containing results
	 */
	private void combatResolution(String in)
	{
		String delim = "[;]+";
		String[] str = in.split(delim);
		if(str[0].equals("MESSAGE"))
		{
			JOptionPane.showMessageDialog(this,
					str[2],
					str[1],
					JOptionPane.INFORMATION_MESSAGE,
					LoadWarrior.getTurtle());
		}

		inCombat = false;
	}

	/**
	 * Sets up panel displaying local warrior statistics
	 * @return JPanel containing local warrior statistics
	 */
	private JComponent setUpLocalWarriorPanel()
	{
		JPanel pnl = new JPanel();
		pnl.setLayout(new BoxLayout(pnl, BoxLayout.Y_AXIS));
		pnl.setAlignmentX(LEFT_ALIGNMENT);

		//Name Label
		pnl.add(new JLabel(" Name: " + localWarrior.getName()));

		//Health Label
		updateHealthDisplay();
		pnl.add(lblHealth);

		//Place of Origin Label
		pnl.add(new JLabel(" Place of Origin: " + localWarrior.getPlaceOfOrigin()));

		//Display Personal Description
		pnl.add(new JLabel(" Personal Description:"));
		JLabel lblPersonalDescription = new JLabel(localWarrior.getFormattedPersonalDescription());
		lblPersonalDescription.setPreferredSize(new Dimension(400, 200));
		lblPersonalDescription.setAlignmentY(TOP_ALIGNMENT);
		pnl.add(lblPersonalDescription);

		pnl.setBorder(BorderFactory.createLineBorder(Color.black));
		return pnl;	
	}

	/**
	 * Set up panel containing combat controls
	 * @return JPanel containing combat controls
	 */
	private JComponent setUpCombatControlPanel()
	{
		JPanel pnl = new JPanel();
		pnl.setLayout(new BoxLayout(pnl, BoxLayout.Y_AXIS));
		pnl.setAlignmentY(CENTER_ALIGNMENT);

		//Attack Controls
		pnl.add(new JLabel(" Combat"));
		JButton btnAttack1 = new JButton(ATTACK1);
		btnAttack1.addActionListener(this);
		pnl.add(btnAttack1);
		JButton btnAttack2 = new JButton(ATTACK2);
		btnAttack2.addActionListener(this);
		pnl.add(btnAttack2);
		JButton btnAttack3 = new JButton(ATTACK3);
		btnAttack3.addActionListener(this);
		pnl.add(btnAttack3);

		//Spacer
		pnl.add(new JLabel("  "));
		pnl.add(new JLabel("  "));

		//Refresh Warriors
		JButton btnRefresh = new JButton("Refresh");
		btnRefresh.addActionListener(this);
		pnl.add(btnRefresh);

		//Spacer
		pnl.add(new JLabel("  "));
		pnl.add(new JLabel("  "));

		//Exit Program
		JButton btnExit = new JButton("Exit");
		btnExit.addActionListener(this);
		pnl.add(btnExit);

		return pnl;
	}

	/**
	 * Builds Panel displaying table containing possible opponents
	 * @return panel containing table of opponents
	 */
	private JComponent setUpWarriorTable()
	{
		pnlOpponents = new JPanel();
		pnlOpponents.add(buildOpponentTable());
		out.println("REFRESH");
		return pnlOpponents;
	}

	/**
	 * Initializes Opponent table and sets column headers and width
	 */
	private JComponent buildOpponentTable()
	{
		String[] header = new String[] {"Name", "Health", "Place of Origin", "Personal Description", "Serial"};
		if (tblOpponents == null)
		{
			tblOpponents = new JTable()
			{
				public boolean isCellEditable(int nRow, int nCol)
				{
					return false;
				}
			};
		}
		tblOpponents.setColumnSelectionAllowed(false);

		DefaultTableModel tableModel = (DefaultTableModel) ((JTable) tblOpponents).getModel();
		tableModel.setColumnIdentifiers(header);
		tblOpponents.setPreferredScrollableViewportSize(new Dimension(560, 1500));
		tblOpponents.getColumnModel().getColumn(0).setPreferredWidth(60);
		tblOpponents.getColumnModel().getColumn(1).setPreferredWidth(10);
		tblOpponents.getColumnModel().getColumn(2).setPreferredWidth(100);
		tblOpponents.getColumnModel().getColumn(3).setPreferredWidth(250);
		tblOpponents.getColumnModel().getColumn(4).setMinWidth(0);
		tblOpponents.getColumnModel().getColumn(4).setMaxWidth(0);
		tblOpponents.getColumnModel().getColumn(4).setWidth(0);

		JScrollPane scrlPane = new JScrollPane(tblOpponents);
		scrlPane.setPreferredSize(new Dimension(600, 250));
		return scrlPane;
	}

	/**
	 * Saves warrior to file and exits application
	 */
	private void exitApplication()
	{
		out.println("CLOSE_CLIENT");
		this.localWarrior.saveWarrior();
		try
		{
			out.close();
			in.close();
			server.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		System.exit(0);
	}

	/**
	 * Control thread that listens for input from server
	 */
	public void run()
	{
		String lineIn;
		try
		{
			while((lineIn = in.readLine())!= null)
			{
				String delim = "[;]+";
				String[] input = lineIn.split(delim,2);
				if(input[0].equals("REFRESH"))
					updateOpponentTable(input[1]);
				if(input[0].equals("RESOLUTION"))
					combatResolution(input[1]);
				if(input[0].equals("UPDATE"))
					updateLocalWarrior(input[1]);
				if(input[0].equals("DEFEND"))
					getDefense(input[1]);
			}
		}
		catch (SocketException e)
		{
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}

	}

	/**
	 * Overrides ActionListener
	 * Provides interactivity to button controls
	 */
	@Override
	public void actionPerformed(ActionEvent event)
	{
		String in = event.getActionCommand();
		if(in.equalsIgnoreCase("Exit"))
			exitApplication();
		else if(in.equalsIgnoreCase("Refresh"))
			out.println("REFRESH");
		else if(in.equalsIgnoreCase(ATTACK1) ||
				in.equalsIgnoreCase(ATTACK2) ||
				in.equalsIgnoreCase(ATTACK3))
			commenceAttack(in);
	}

	/**
	 * Main Method
	 * Creates a new Load Warrior class
	 */
	public static void main(String[] args)
	{
		new LoadWarrior();
	}
}

/**
 * LoadWarrior is shown when the user first runs the program. It allows the user to
 * create or load a warrior, then enter the arena.
 */
@SuppressWarnings("serial")
class LoadWarrior extends JFrame implements ActionListener
{
	//Warrior
	private JLabel lblName, lblHealth, lblPlaceOfOrigin, lblPersonalDescription;
	private Warrior currentWarrior;

	//Message Icon
	final static private ImageIcon TURTLE_ICON = new ImageIcon(System.getProperty("user.dir") + 
			File.separator + "src" + 
			File.separator + "turtle_small.JPG");

	/**
	 * Constructor
	 * Creates and displays basic warrior client dialog allowing the user to create or
	 * load a warrior and join combat
	 */
	public LoadWarrior()
	{
		//Setup panel
		this.setLayout(new FlowLayout());
		this.setTitle("Warrior Combat (SEN632)");
		this.getContentPane().add(setUpControlPanel());
		JPanel spacer = new JPanel();
		spacer.setSize(new Dimension(100, 100));
		this.getContentPane().add(spacer);
		this.getContentPane().add(setUpCurrentWarriorPanel());
		this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
		this.addWindowListener(new WindowListener(){
			@Override
			public void windowClosed(WindowEvent arg0) {}
			@Override
			public void windowClosing(WindowEvent arg0) {
				exitApplication();
			}
			@Override
			public void windowDeactivated(WindowEvent arg0) {}
			@Override
			public void windowDeiconified(WindowEvent arg0) {}
			@Override
			public void windowIconified(WindowEvent arg0) {}
			@Override
			public void windowOpened(WindowEvent arg0) {}
			@Override
			public void windowActivated(WindowEvent e) {}
		});

		//Display frame
		this.pack();
		this.setLocationRelativeTo(null);
		this.setVisible(true);
	}

	/**
	 * Dialog box to get IP address from user
	 * @return IP address
	 */
	private String getIPAddress()
	{
		return (String)JOptionPane.showInputDialog(
				this,
				"Please enter the server IP Address:",
				"",
				JOptionPane.PLAIN_MESSAGE,
				TURTLE_ICON,
				null,
				"");
	}

	/**
	 * Returns the turtle Icon for use in dialogs
	 * @return turtle icon
	 */
	public static ImageIcon getTurtle()
	{
		return TURTLE_ICON;
	}

	/**
	 * Changes the CurrentWarrior to a given Warrior and updates display
	 * @param warrior new warrior
	 */
	public void setCurrentWarrior(Warrior warrior)
	{
		currentWarrior = warrior;
		updateCurrentWarrior();
	}

	/**
	 * sets up left side panel allowing user to create or load a warrior
	 * and enter combat arena
	 * @return	pnlControl	Panel containing option buttons
	 */
	private JComponent setUpControlPanel()
	{
		JPanel pnlControl = new JPanel(new BorderLayout());
		pnlControl.setSize(new Dimension(100, 100));
		JButton btnLoadWarrior = new JButton("Load Warrior");
		btnLoadWarrior.addActionListener(this);
		pnlControl.add(btnLoadWarrior, BorderLayout.NORTH);
		JButton btnNewWarrior = new JButton("New Warrior");
		btnNewWarrior.addActionListener(this);
		pnlControl.add(btnNewWarrior, BorderLayout.CENTER);
		JButton btnJoinCombat = new JButton("Join Combat");
		btnJoinCombat.addActionListener(this);
		pnlControl.add(btnJoinCombat, BorderLayout.SOUTH);

		return pnlControl;
	}

	/**
	 * Display Panel containing currently loaded warrior
	 * @return	pnlCurrentWarrior	Panel displaying HP, Origin, and Description
	 */
	private JComponent setUpCurrentWarriorPanel()
	{
		JPanel pnlCurrentWarrior = new JPanel();
		pnlCurrentWarrior.setLayout(new BoxLayout(pnlCurrentWarrior, BoxLayout.Y_AXIS));
		pnlCurrentWarrior.setAlignmentX(LEFT_ALIGNMENT);

		//Display Name
		JPanel pnlName = new JPanel();
		pnlName.setLayout(new BoxLayout(pnlName, BoxLayout.X_AXIS));
		pnlName.setAlignmentX(LEFT_ALIGNMENT);
		pnlName.add(new JLabel(" Name: "));
		lblName = new JLabel("");
		pnlName.add(lblName);
		pnlCurrentWarrior.add(pnlName);

		//Display Health
		JPanel pnlHealth = new JPanel();
		pnlHealth.setLayout(new BoxLayout(pnlHealth, BoxLayout.X_AXIS));
		pnlHealth.setAlignmentX(LEFT_ALIGNMENT);
		pnlHealth.add(new JLabel(" Health: "));
		lblHealth = new JLabel("0");
		pnlHealth.add(lblHealth);
		pnlCurrentWarrior.add(pnlHealth);

		//Display Place of Origin
		JPanel pnlPlaceOfOrigin = new JPanel();
		pnlPlaceOfOrigin.setLayout(new BoxLayout(pnlPlaceOfOrigin, BoxLayout.X_AXIS));
		pnlPlaceOfOrigin.setAlignmentX(LEFT_ALIGNMENT);
		pnlPlaceOfOrigin.add(new JLabel(" Place of Origin: "));
		lblPlaceOfOrigin = new JLabel("");
		pnlPlaceOfOrigin.add(lblPlaceOfOrigin);
		pnlCurrentWarrior.add(pnlPlaceOfOrigin);

		//Display Personal Description
		JPanel pnlPersonalDescription = new JPanel();
		pnlPersonalDescription.setLayout(new BoxLayout(pnlPersonalDescription, BoxLayout.Y_AXIS));
		pnlPersonalDescription.setAlignmentX(LEFT_ALIGNMENT);
		pnlPersonalDescription.add(new JLabel(" Personal Description:"));
		JPanel pnlDescriptionPane = new JPanel();
		pnlDescriptionPane.setLayout(new BoxLayout(pnlDescriptionPane, BoxLayout.X_AXIS));
		pnlDescriptionPane.setAlignmentX(LEFT_ALIGNMENT);
		pnlDescriptionPane.setPreferredSize(new Dimension(400,200));
		lblPersonalDescription = new JLabel("");
		pnlDescriptionPane.add(lblPersonalDescription);
		pnlPersonalDescription.add(pnlDescriptionPane);
		pnlCurrentWarrior.add(pnlPersonalDescription);
		pnlCurrentWarrior.setBorder(BorderFactory.createLineBorder(Color.black));
		return pnlCurrentWarrior;
	}

	/**
	 * Updates the display to show the currently selected warrior
	 */
	private void updateCurrentWarrior()
	{
		if(currentWarrior == null || currentWarrior.getName().equalsIgnoreCase(""))
			currentWarrior = null;
		else
		{
			lblName.setText(currentWarrior.getName());
			lblHealth.setText(currentWarrior.getHealth());
			lblPlaceOfOrigin.setText(currentWarrior.getPlaceOfOrigin());
			lblPersonalDescription.setText(currentWarrior.getFormattedPersonalDescription());
			this.pack();
		}
	}

	/**
	 * Gets server IP from user and attempts to connect
	 */
	private void initiateServerConnection()
	{
		String ip = getIPAddress();

		//for debugging use, uses local machine for server IP
		/*String ip = null;
		try {
			ip = InetAddress.getLocalHost().getHostAddress();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}*/

		while(!isValidIP(ip))
		{
			JOptionPane.showMessageDialog(this,
					"Please enter a valid IP Address",
					"Invalid IP",
					JOptionPane.INFORMATION_MESSAGE,
					TURTLE_ICON);

			ip = getIPAddress();
		}

		try
		{
			InetAddress host = InetAddress.getByName(ip);
			new ArenaClient(new Socket(host.getHostName(), ArenaClient.getPort()), currentWarrior);
			this.dispose();
		}
		catch (Exception e)
		{
			JOptionPane.showMessageDialog(this,
					"The specified arena is currently closed",
					"Unable to connect to server",
					JOptionPane.INFORMATION_MESSAGE,
					TURTLE_ICON);
		}

	}

	/**
	 * Checks whether the entered string is a valid IP address
	 * @param ip string to be validated
	 * @return true id IP is valid
	 */
	private boolean isValidIP(String ip)
	{
		String[] octets = ip.split("[.]+");
		if(octets.length != 4)
			return false;
		for(String octet : octets)
			if(Integer.parseInt(octet)<0 || Integer.parseInt(octet)>255)
				return false;
		return true;
	}

	/**
	 * save the current warrior to a file and exits the application
	 */
	private void exitApplication()
	{
		if(currentWarrior != null)
			currentWarrior.saveWarrior();
		System.exit(0);
	}

	/**
	 * Overrides ActionListener method
	 * Provides responses when a button is pressed
	 * @param	event	Action triggering method
	 */
	@Override
	public void actionPerformed(ActionEvent event)
	{
		String in = event.getActionCommand();
		if(in.equalsIgnoreCase("New Warrior"))
		{
			NewWarrior.createNewWarriorGUI(this);
		}
		else if(in.equalsIgnoreCase("Load Warrior"))
		{
			currentWarrior = new Warrior();
			updateCurrentWarrior();
		}
		else if(in.equalsIgnoreCase("Join Combat"))
		{
			if(currentWarrior != null )
			{
				if(Integer.parseInt(currentWarrior.getHealth()) == 0)
					JOptionPane.showMessageDialog(this,
							"You cannot enter the arena with a dead warrior.",
							"ERROR: Are you a Ghost?",
							JOptionPane.INFORMATION_MESSAGE,
							TURTLE_ICON);							
				else
					initiateServerConnection();
			}
			else
			{
				JOptionPane.showMessageDialog(this,
						"How can you fight without a warrior?",
						"ERROR: You are Unarmed",
						JOptionPane.INFORMATION_MESSAGE,
						TURTLE_ICON);
			}
		}
	}
}

/**
 * Creates a Dialog that allows a user to generate a new Warrior
 */
@SuppressWarnings("serial")
class NewWarrior extends JFrame implements ActionListener
{
	JTextField tfName, tfPlaceOfOrigin;
	JTextArea taPersonalDescription;
	LoadWarrior warCli;

	/**
	 * Constructor
	 * creates a NewWarrior Object and displays
	 * @param warCli Client requesting new Warrior
	 */
	private NewWarrior(LoadWarrior warCli)
	{
		this.warCli = warCli;

		//Setup panel
		this.setLayout(new BorderLayout());
		this.setTitle("Create New Warrior");
		JPanel content = new JPanel();
		content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
		content.setAlignmentX(LEFT_ALIGNMENT);

		//Name Field
		content.add(new JLabel("Name: "));
		this.tfName = new JTextField();
		content.add(tfName);

		//Place of Origin Field
		content.add(new JLabel("Place of Origin:"));
		this.tfPlaceOfOrigin = new JTextField();
		content.add(tfPlaceOfOrigin);

		//Personal Description Field
		content.add(new JLabel("Personal Description:"));
		this.taPersonalDescription = new JTextArea();
		this.taPersonalDescription.setPreferredSize(new Dimension(400,200));
		this.taPersonalDescription.setLineWrap(true);
		content.add(taPersonalDescription);

		//Control Buttons
		JPanel pnlButtons = new JPanel(new FlowLayout());
		JButton btnAccept = new JButton("Accept");
		btnAccept.addActionListener(this);
		pnlButtons.add(btnAccept);
		JButton btnCancel = new JButton("Cancel");
		btnCancel.addActionListener(this);
		pnlButtons.add(btnCancel);
		content.add(pnlButtons);

		this.getContentPane().add(content);
		this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
		this.addWindowListener(new WindowListener(){
			@Override
			public void windowClosed(WindowEvent arg0) {}
			@Override
			public void windowClosing(WindowEvent arg0) {
				cancelAction();
			}
			@Override
			public void windowDeactivated(WindowEvent arg0) {}
			@Override
			public void windowDeiconified(WindowEvent arg0) {}
			@Override
			public void windowIconified(WindowEvent arg0) {}
			@Override
			public void windowOpened(WindowEvent arg0) {}
			@Override
			public void windowActivated(WindowEvent e) {}
		});

		//Display Frame
		this.pack();
		this.setLocationRelativeTo(null);
		this.setVisible(true);
	}

	/**
	 * creates the new warrior GUI
	 * @param warCli Client server requesting new warrior
	 */
	public static void createNewWarriorGUI(LoadWarrior warCli)
	{
		new NewWarrior(warCli);
	}

	/**
	 * Cancels action and destroys window
	 */
	private void cancelAction()
	{
		dispose();
	}

	/**
	 * Overrides ActionListener method
	 * Provides responses when a button is pressed
	 * @param	event	Action triggering method
	 */
	@Override
	public void actionPerformed(ActionEvent event) {
		String in = event.getActionCommand();
		if(in.equalsIgnoreCase("Accept"))
		{
			String name = tfName.getText();
			String placeOfOrigin = tfPlaceOfOrigin.getText();
			String personalDescription = taPersonalDescription.getText();

			//Validate Data has been entered
			if (name.equalsIgnoreCase("") || 
					placeOfOrigin.equalsIgnoreCase("") || 
					personalDescription.equalsIgnoreCase(""))
				JOptionPane.showMessageDialog(this,
						"One or more fields have not been completed",
						"Incomplete Warrior",
						JOptionPane.INFORMATION_MESSAGE,
						LoadWarrior.getTurtle());

			else
			{
				warCli.setCurrentWarrior(new Warrior(name, placeOfOrigin, personalDescription));
				dispose();
			}
		}
		if(in.equalsIgnoreCase("Cancel"))
			cancelAction();
	}

}



